package com.geekgo.gges.service.impl;

import com.alibaba.fastjson.JSON;
import com.geekgo.gges.model.Article;
import com.geekgo.gges.model.City;
import com.geekgo.gges.repository.ArticleRepository;
import com.geekgo.gges.service.ArticleService;
import org.apache.commons.collections4.IterableUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by Administrator on 2018/5/1.
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    private final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);


    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Long  saveArticle(Article article){
        Article save = articleRepository.save(article);
        return save.getId();
    }

    @Override
    public List<Article> searchAll() {
        Iterable<Article> iterable = articleRepository.findAll();
        return IterableUtils.toList(iterable);
    }

    @Override
    public List<Article> queryByString(String word) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.queryStringQuery(word)).build();
        List<Article> articleList = elasticsearchTemplate.queryForList(searchQuery,Article.class);
        return articleList;
    }

    @Override
    public List<Article> queryByMatch(String word) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("title", word)).build();
        List<Article> objects = elasticsearchTemplate.queryForList(searchQuery,Article.class);
        logger.info("查询结果：{}", JSON.toJSONString(objects));
        return objects;
    }
}
